package com.google.code.mochaccino.framework.dbtool.liquibase;
/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.inject.Inject;
import javax.sql.DataSource;
import liquibase.database.Database;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.Dialect;

public class LiquibaseProviderHibernate implements LiquibaseProvider {

	private Configuration configuration = null;
	private DataSource    dataSource    = null;
	private Database      db            = null;
	private Dialect       dialect       = null;

	@Inject
	public LiquibaseProviderHibernate( DataSource ds, Configuration configuration ) {
		this.dataSource = ds;
		this.configuration = configuration;
	}

	public void createSchema() {
		try {
			executeScripts( configuration.generateSchemaCreationScript( dialect ) );
		} catch ( SQLException e ) {
			throw new RuntimeException( e );
		}
	}

	private void executeScripts( String[] createScript ) throws SQLException {
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = dataSource.getConnection();
			stmt = conn.createStatement();
			for ( String sql : createScript ) {
				stmt.executeUpdate( sql );
			}
			conn.commit();
		} catch ( SQLException e ) {
			conn.rollback();
			throw new RuntimeException( e );
		} finally {

			if ( stmt != null ) {
				stmt.close();
			}

			if ( conn != null ) {
				conn.close();
			}
		}
	}

	@Override
	public void destroy() throws Exception {
		if ( db != null ) {
			db.close();
		}
		configuration = null;
		dialect = null;
	}

	public void dropSchema() {
		try {
			executeScripts( configuration.generateDropSchemaScript( dialect ) );
		} catch ( SQLException e ) {
			throw new RuntimeException( e );
		}
	}

	@Override
	public Database getDatabase() {
		return db;
	}

	@Override
	public void initialize() throws Exception {
		db = DatabaseFactory.getInstance().findCorrectDatabaseImplementation( new JdbcConnection( dataSource.getConnection() ) );
		if ( db == null ) {
			throw new RuntimeException( "Could not find Database Implementation!" );
		}

		try {
			this.dialect = (Dialect) Class.forName( configuration.getProperties().getProperty( Environment.DIALECT ) ).newInstance();
		} catch ( InstantiationException e ) {
			throw new RuntimeException( e );
		} catch ( IllegalAccessException e ) {
			throw new RuntimeException( e );
		} catch ( ClassNotFoundException e ) {
			throw new RuntimeException( e );
		}
	}
}
